<?php

/**
 * 因为不喜欢使用 laravel-auth
 * 所以自己重新封装一下 后端登录验证
 * Created by PhpStorm
 * User Niu Yong Qiang
 * Date 2021/9/16 15:39
 */

namespace App\Http\Middleware;

use App\Models\BreederUserModel;
use App\Models\UserModel;
use App\Models\UserTokenModel;
use Closure;

class BreederApiAuth
{
    /**
     * @param $request
     * @param Closure $next
     * @return \Illuminate\Http\JsonResponse|mixed
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function handle($request, Closure $next)
    {
        //根据token,获取用户信息
        $params = $request->header('token');

        $where[] = ['token', $params ?? -1];
        $where[] = ['status', 2];
        $tokenLogs = UserTokenModel::getUserOne($where);

        if (empty($tokenLogs['user_id'])){
            //没有权限登录，走code
            return response()->json([
                'code' => 1001,
                'message' => '登录状态失效',
                'data' => []
            ]);
        }

        //存缓存
        if (empty(adminBreederInfo('id'))){
            //根据user_id获取用户信息
            $userOne = BreederUserModel::getOneById($tokenLogs['user_id']);
            session()->put('adminBreederInfo', $userOne);
        }

        return $next($request);
    }

}

